package com.huiminpay.merchant.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.StringUtil;
import com.huiminpay.merchant.common.SecurityUtil;
import com.huiminpay.merchant.convert.MerchantConvert;
import com.huiminpay.merchant.dto.MerchantDTO;
import com.huiminpay.common.cache.exception.BizException;
import com.huiminpay.merchant.service.IMerchantService;
import com.huiminpay.merchant.vo.MerchantRegVo;
import com.huiminpay.merchant.vo.MerchantVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wsk
 * @since 2021-06-07
 */
@Slf4j
@RestController
@Api(value = "商户操作相关", tags = "商户操作相关", description = "商户操作相关1")
public class MerchantController {

    @Reference
    public IMerchantService merchantService;

    @Autowired
    RestTemplate restTemplate;

    @Value("${sms.url}")
    private String smsUrl;

    @Value("${sms.effectiveTime}")
    private String effectiveTime;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.domain}")
    private String domain;

    @ApiImplicitParam(name = "id", example = "1", dataType = "Long")
    @ApiOperation(value = "根据ID查询商户信息", tags = {"根据ID查询商户信息"})
    @GetMapping("/my/merchants")
    public MerchantVo findMerchantById() {

        Long merchantId = SecurityUtil.getMerchantId();
        log.info("[{}]",merchantId);

        MerchantDTO merchantDto = merchantService.findMerchantById(merchantId);
//        MerchantVo merchantVo = new MerchantVo();
//        BeanUtils.copyProperties(merchantDto, merchantVo);
        return MerchantConvert.INSTANCE.dto2vo(merchantDto);
    }



    @ApiOperation(value = "商户注册")
    @PostMapping("/merchants/register")
    public MerchantVo reg(@RequestBody MerchantRegVo merchantRegVo) {
//        1.非空验证
        if (merchantRegVo.getUsername().isEmpty()) {
//            throw new RuntimeException("用户名不能为空！");
            throw new BizException(CommonErrorCode.E_100002);
        }
        if (merchantRegVo.getPassword().isEmpty()) {
//            throw new RuntimeException("密码不能为空！");
            throw new BizException(CommonErrorCode.E_200232);
        }
        if (merchantRegVo.getMobile().isEmpty()) {
//            throw new RuntimeException("手机号不能为空！");
            throw new BizException(CommonErrorCode.E_200230);
        }
        if (merchantRegVo.getCode().isEmpty()) {
//            throw new RuntimeException("验证码不能为空！");
            throw new BizException(CommonErrorCode.E_100103);
        }
        //2.验证码校验
        String code = merchantRegVo.getCode();
        String key = merchantRegVo.getKey();
        String url = smsUrl + "/verify?name=sms&verificationCode=" + code + "&verificationKey=" + key;
        String s = restTemplate.postForObject(url, null, String.class);
        JSONObject jsonObject = JSON.parseObject(s);
        if (!jsonObject.getBoolean("result")) {
//            throw new RuntimeException("验证码错误！");
            throw new BizException(CommonErrorCode.E_100102);
        }



        //3.注册

        MerchantDTO merchantDTO = new MerchantDTO();
        BeanUtils.copyProperties(merchantRegVo, merchantDTO);

        MerchantDTO merchantDTO1 = merchantService.regMch(merchantDTO);
        MerchantVo merchantVo = new MerchantVo();
        BeanUtils.copyProperties(merchantDTO1, merchantVo);
        return merchantVo;
    }

    @ApiOperation(value = "短信验证码发送")
    @GetMapping("sms")
    public String smsSend(String phone) {

        //非空校验
        if (StringUtil.isEmpty(phone)) {
//            throw new RuntimeException("手机号不能为空！");
            throw new BizException(CommonErrorCode.E_200230);
        }

        //发送验证码
        String url = smsUrl + "/generate?effectiveTime=" + effectiveTime + "&name=sms";

        Map<String, Object> map = new HashMap<>();
        map.put("mobile", phone);//要发送的手机号码

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json");
        HttpEntity httpEntity = new HttpEntity(map,httpHeaders);
        String s = restTemplate.postForObject(url, httpEntity, String.class);
        String key = null;
        try {
            JSONObject jsonObject = JSON.parseObject(s);
            JSONObject result = jsonObject.getJSONObject("result");
            key = result.getString("key");
        } catch (Exception e) {
            e.printStackTrace();
//            throw new RuntimeException("发送失败");
            throw new BizException(CommonErrorCode.E_100003);
        }
        return key;
    }

    @ApiOperation(value = "文件上传")
    @PostMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {

        if (file == null) {
//            throw new RuntimeException("文件不存在");
            throw new BizException(CommonErrorCode.E_100004);
        }

        String filename = file.getOriginalFilename();
        String s = filename.substring(filename.lastIndexOf("."));

        String fileName = System.currentTimeMillis() + s;
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        // 阿里云账号AccessKey拥有所有APlI的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);


        // 创建PutObjectRequest对象。
        // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getInputStream());

        // 上传字符串。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();

        return domain + fileName;
    }

    @ApiOperation("资质申请")
    @PostMapping("/my/merchants/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantVo", value = "商户认证资料", required = true, dataType = "MerchantVo", paramType = "body")
    })
    public MerchantVo apply(@RequestBody MerchantVo merchantVo) {

//        1.非空校验
        if (StringUtil.isEmpty(merchantVo.getMerchantName())){
//            throw new RuntimeException("商户名不能为空！");
            throw new BizException(CommonErrorCode.E_100001);
        }
//        2.更新数据库

//        MerchantDTO merchantDTO = new MerchantDTO();
//        BeanUtils.copyProperties(merchantVo,merchantDTO);

        MerchantDTO merchantDTO = MerchantConvert.INSTANCE.vo2dto(merchantVo);

        Long merchantId = SecurityUtil.getMerchantId();
        merchantDTO.setId(merchantId);
        MerchantDTO merchantDTO1 = merchantService.apply(merchantDTO);

//        BeanUtils.copyProperties(merchantDTO1,merchantVo);
        MerchantVo merchantVo1 = MerchantConvert.INSTANCE.dto2vo(merchantDTO1);
        return merchantVo1;
    }

}
